package com.mystudy.concurrent.classLoader;

import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * TODO: 自定义的类加载器
 * 1.加载器的委托是优先交给父加载器去尝试加载
 * 2.父加载器和自家在其其实是一种包装关系或者包含关系，并不一定是继承
 * @author acy
 * @since 2019/05/31 17:33
 */
@Getter
@Setter
public class MyClassLoader extends ClassLoader {
	//默认的文件路径
	private static final String DEFAULT_DIR = "C:\\IdeaWorkSpeace\\myStudyTest\\classLoaderTest\\";

	private String dir = DEFAULT_DIR;

	//加载器名
	private String classLoaderName;

	public MyClassLoader(String classLoaderName) {
		super();
		this.classLoaderName = classLoaderName;
	}

	public MyClassLoader(ClassLoader parent, String classLoaderName) {
		super(parent);
		this.classLoaderName = classLoaderName;
	}

	public MyClassLoader() {
		super();
	}

	/**
	 * @param name 类的权限定名
	 * @return
	 * @throws ClassNotFoundException
	 */
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String classPath = name.replace(".", "/");
		File file = new File(dir, classPath + ".class");
		if (!file.exists()) {
			throw new ClassNotFoundException("the class" + name + "not fund");
		}
		byte[] bytes = loadClassByBytes(file);
		if (null == bytes || bytes.length == 0) {
			throw new ClassNotFoundException("load class" + name + "failed");
		}
		return this.defineClass(name, bytes, 0, bytes.length);
	}

	private byte[] loadClassByBytes(File file) {
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
			 FileInputStream inputStream = new FileInputStream(file)) {
			byte[] bytes = new byte[1024];
			int length = 0;
			//读到文件的末尾的时候为-1
			while ((length=inputStream.read(bytes))!=-1){
				baos.write(bytes,0,length);
			}
			baos.flush();
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
